// 106. 从中序与后序遍历序列构造二叉树


#include <vector>
using namespace std;

struct TreeNode 
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution
{
public:
    TreeNode* _build(vector<int>& inorder, vector<int>& postorder,
                    int& prei, int inbegin, int inend)
    {
        if(inbegin > inend) return nullptr;

        int rooti = inbegin;
        while(rooti <= inend)
        {
            if(postorder[prei] == inorder[rooti]) break;
            rooti++;
        }
        // 后序确定根
        TreeNode* root = new TreeNode(postorder[prei--]);

        // [inbegin, rooti-1] rooti [rooti+1, inend]
        // 中序分割确定左右子树
        // 后续：左右根，因此先右再左
        root->right = _build(inorder, postorder, prei, rooti + 1, inend);
        root->left = _build(inorder, postorder, prei, inbegin, rooti - 1); 

        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder)
    {
        int size = inorder.size() - 1;
        // 范围为左闭右闭
        return _build(inorder, postorder, size, 0, size);
    }
};